package com.email.crontab.common.service.impl;

import com.email.crontab.common.domain.InlineResource;
import com.email.crontab.common.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

@Service
public class MailServiceImpl implements MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String formMail;

    @Value("${spring.mail.name}")
    private String name;

    /**
     * 发送简单邮件
     *
     * @param toMail
     * @param subject
     * @param content 邮件内容
     */
    @Override
    public void sendSimpleMail(String toMail, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(formMail);
        simpleMailMessage.setTo(toMail);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        try {
            sender.send(simpleMailMessage);
            logger.info("发送给" + toMail + "简单邮件已经发送。 subject：" + subject);
        } catch (Exception e) {
            logger.info("发送给" + toMail + "send mail error subject：" + subject);
            e.printStackTrace();
        }
    }

    /**
     * 发送 html 格式邮件
     *
     * @param toMail
     * @param subject
     * @param content 邮件内容
     */
    @Override
    public void sendHtmlMail(String toMail, String subject, String content) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setTo(toMail);
            mimeMessageHelper.setFrom(formMail);
            mimeMessageHelper.setText(content, true);
            mimeMessageHelper.setSubject(subject);
            sender.send(mimeMessage);
            logger.info("发送给" + toMail + "html邮件已经发送。 subject：" + subject);
        } catch (MessagingException e) {
            logger.info("发送给" + toMail + "html send mail error subject：" + subject);
            e.printStackTrace();
        }
    }

    /**
     * 发送静态资源（一般是图片）的邮件
     *
     * @param to
     * @param subject
     * @param content     邮件内容，需要包括一个静态资源的id，比如：<img src=\"cid:image\" >
     * @param resourceist 静态资源list
     */
    @Override
    public void sendInlineResourceMail(String to, String subject, String content, List<InlineResource> resourceist) {
        this.sendInlineResourceMail(to, null, subject, content, resourceist);
    }

    @Override
    public void sendInlineResourceMail(String to, String[] cc, String subject, String content, List<InlineResource> resourceist) {
        MimeMessage message = sender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(formMail);
            helper.setTo(to);
            if (cc != null && cc.length > 0) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            helper.setText(content, true);
            for (InlineResource inlineResource : resourceist) {
                FileSystemResource res = new FileSystemResource(new File(inlineResource.getPath()));
                helper.addInline(inlineResource.getCid(), res);
            }
            sender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常！", e);
        }
    }

    /**
     * 发送带附件的邮件
     * 发送带附件的邮件和发送html 操作基本一致，通过MimeMessageHelper设置邮件信息的时候，
     * 将附件通过FileSystemResource 进行包装，然后再通过 MimeMessageHelper addAttachment 设置到发送邮件信息中即可。
     *
     * @param toMail
     * @param subject
     * @param content 邮件内容
     */
    @Override
    public void sendAttachmentsMail(String toMail, String subject, String content, String filePath) {
        this.sendAttachmentsMail(toMail, null, subject, content, filePath);
    }

    @Override
    public void sendAttachmentsMail(String toMail, String[] cc, String subject, String content, String filePath) {
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(formMail);
            helper.setTo(toMail);
            if (cc != null && cc.length > 0) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf("/"));
            helper.addAttachment(fileName, file);
            sender.send(message);
            logger.info("发送给" + toMail + "带附件的邮件已经发送。");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("发送给" + toMail + "带附件的邮件时发生异常！", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String[] toMail, String[] cc, String subject, String content, List<String> filePaths) {
        System.setProperty("mail.mime.splitlongparameters","false");
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(name+'<'+formMail+'>');
            if (toMail != null && toMail.length>0){
                helper.setTo(toMail);
            }
            if (cc != null && cc.length > 0) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            helper.setText(content, true);
            for (String filePath : filePaths) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String[] filePathL = filePath.split("/");
                helper.addAttachment(filePathL[filePathL.length-1], file);
            }
            sender.send(message);
            logger.info("发送给" + Arrays.toString(toMail) + "带附件的邮件已经发送。");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("发送给" + toMail + "带附件的邮件时发生异常！", e);
        }
    }
}
